/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.resource;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.ResBean;
import com.sinodata.bsm.center.bean.ResTypeBean;
import com.sinodata.bsm.center.cache.CollectFieldCache;
import com.sinodata.bsm.center.cache.DataTypeCache;
import com.sinodata.bsm.center.cache.PropertyCache;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.resource.PropertyService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.exception.AppException;
import com.sinodata.bsm.common.vo.CollectField;
import com.sinodata.bsm.common.vo.DataType;
import com.sinodata.bsm.common.vo.Property;
import com.sinodata.bsm.common.vo.Res;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author fanshengchao
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-7-9 上午10:55:53          fanshengchao        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class PropertyAction extends BaseAction<Property> {

    private Property entity;
    private Long id;

    @Autowired
    private PropertyService propertyService;
    @Autowired
    private DataTypeCache dataTypeCache;
    @Autowired
    private PropertyCache propertyCache;
    @Autowired
    private CollectFieldCache collectFieldCache;

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#delete()
     */
    @Override
    public String delete() throws Exception {
        Property property = propertyService.getProperty(id);
        JSONObject object = new JSONObject();
        if (isDeleted(id)) {
            object.element("flag", "false");
            object.element("info", "指标已被删除");
        } else {
            //用户自定义的指标
            List<Property> propertys = propertyService.findPropertyByResId(property.getResId());

            //如果自定义字段有被引用
            Boolean quoteFlag = false;
            for (int i = 0; propertys != null && i < propertys.size(); i++) {
                Property entity = propertys.get(i);
                CollectField field = collectFieldCache.getByPropId(entity.getId());
                if (field != null && field.getProp().longValue() == id.longValue()) {
                    quoteFlag = true;
                    break;
                }
            }
            if (quoteFlag == false) {
                object.element("flag", "true");
                //删除自定义指标 
                propertyService.deletePropertyById(id);
            } else {
                object.element("flag", "false");
                object.element("info", "指标已被引用,不能删除");
            }
        }
        Struts2Utils.renderJson(object);
        return null;
    }

    /**
     * true 
     * @param propId
     * @return
     */
    private boolean isDeleted(Long propId) {
        return propertyService.getProperty(id) == null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#input()
     */
    @Override
    public String input() throws Exception {
        List<DataType> dataTypes = dataTypeCache.getAll();
        Struts2Utils.setRequestAttribute("dataTypes", dataTypes);
        Struts2Utils.setRequestAttribute("resId", Struts2Utils.getParameter("resId"));
        return "input";
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#list()
     */
    @Override
    public String list() throws Exception {
        Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));
        JSONObject json = new JSONObject();

        List<Property> propertys = propertyService.findPropertyByResId(resId);
        JSONArray array = new JSONArray();
        for (int i = 0; propertys != null && i < propertys.size(); i++) {
            JSONObject entity = new JSONObject();
            Property property = propertys.get(i);
            entity.element("operate", "");
            entity.element("name", property.getName());
            entity.element("code", property.getCode());

            DataType dataType = dataTypeCache.get(property.getDataTypeId());
            entity.element("dataTypeName", dataType.getName());
            entity.element("desc", property.getDesc() == null ? "" : property.getDesc());
            entity.element("id", property.getId());
            array.add(entity);
        }

        json.element("aaData", array);
        json.element("iTotalRecords", 0);
        json.element("iTotalDisplayRecords", 0);

        Struts2Utils.renderText(json.toString());
        return null;
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#prepareModel()
     */
    @Override
    protected void prepareModel() throws Exception {
        if (id == null) {
            entity = new Property();
        } else {
            entity = propertyService.getProperty(id);
        }
    }

    /* (non-Javadoc)
     * @see com.sinodata.bsm.center.web.action.BaseAction#save()
     */
    @Override
    public String save() throws Exception {
        try {
            if (entity.getId() == null) {
                List<Property> respropertys = propertyService.findPropertyByResId(entity.getResId());
                Res res = ResBean.get(entity.getResId()).res();
                List<Property> restypepropList = ResTypeBean.get(res.getResTypeId()).properties();
                int store = 0;
                for (int i = 0; restypepropList != null && i < restypepropList.size(); i++) {
                    if (restypepropList.get(i).getStore() > store) {
                        store = restypepropList.get(i).getStore();
                    }
                }
                int maxstore = 201;
                if (respropertys != null && respropertys.size() > 0) {
                    for (Property prop : respropertys) {
                        if (prop.getStore() != null && prop.getStore() < maxstore) {
                            maxstore = prop.getStore();
                        }
                    }
                }
                maxstore = maxstore - 1;
                if (maxstore > store) {
                    entity.setStore(maxstore);
                } else {
                    logger.error("error genernate property store!");
                    throw new AppException("指标存储字段已被占用!请管理员检查。");
                }
                entity.setDisplay(0);
            }
            if (entity.getStore() == null) {
                throw new AppException("指标存储字段未能设置。");
            }
            propertyService.saveOrUpdateProperty(entity);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public String common() {
        Long resId = Long.parseLong(Struts2Utils.getParameter("resId"));
        boolean hasPrivilege = UserFunctionValidate.resFunctionValidate(resId, FunctionConstants.EDIT_RES);
        Struts2Utils.setRequestAttribute("hasEditResPrivilege", hasPrivilege);
        Struts2Utils.setRequestAttribute("resId", resId);
        return "common";
    }

    public String initUpdate() {
        List<DataType> dataTypes = dataTypeCache.getAll();

        Property property = propertyService.getProperty(id);
        Struts2Utils.setRequestAttribute("dataTypes", dataTypes);
        Struts2Utils.setRequestAttribute("property", property);
        Struts2Utils.setRequestAttribute("resId", Struts2Utils.getParameter("resId"));
        return "update";
    }

    /**
     * 指标是否删除
     * 
     * @return true:已删除 false:未删除
     */
    public String isDelete() {
        Struts2Utils.renderText(" " + (propertyService.getProperty(id) == null) + " ");
        return null;
    }

    /**
     * 属性名称重复验证
     * @return
     */
    public String repeatNameValidate() {
        try {
            String name = Struts2Utils.getParameter("name");
            boolean flag = false;
            String resId = Struts2Utils.getParameter("resId");
            List<Property> propertys = new ArrayList<Property>();
            if (resId != null && !resId.equals("")) {
                propertys = propertyService.findPropertyByResId(Long.parseLong(resId));
            } else {
                propertys = propertyCache.getAll();
            }
            Property entity = propertyService.getProperty(id);
            for (int i = 0; propertys != null && i < propertys.size(); i++) {
                Property property = propertys.get(i);
                if (property.getName().equals(name) && entity == null) {
                    flag = true;
                    break;
                }

                //修改时验证
                if (entity != null && property.getId().intValue() != entity.getId().intValue() && name.equals(property.getName())) {
                    flag = true;
                    break;
                }
            }
            Struts2Utils.renderText("" + flag + "");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /* (non-Javadoc)
     * @see com.opensymphony.xwork2.ModelDriven#getModel()
     */
    @Override
    public Property getModel() {
        // TODO Auto-generated method stub
        return entity;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

}
